import BigFileService from './api.ts'

class BigFileUploader {
  constructor(options) {
    this.chunkSize = options.chunkSize || 1 * 1024 * 1024 // 默认5MB
    this.concurrent = options.concurrent || 3 // 默认并发数3
    this.chunks = [] // 文件分片
    this.uploadingQueue = [] // 上传队列
    this.uploadedChunks = [] // 已上传的分片
    this.file = null // 文件对象
    this.fileHash = '' // 文件哈希
    // 进度信息
    this.loaded = 0 // 已上传的字节数
    this.progressCallback = null
  }

  // 选择文件
  async selectFile(file) {
    this.file = file
    await this.calculateHash() // 计算文件哈希(可选)
    this.chunks = this.createChunks(file)
  }

  // 创建文件分片
  createChunks(file) {
    const chunks = []
    let cur = 0
    while (cur < file.size) {
      chunks.push({
        index: chunks.length,
        chunk: file.slice(cur, cur + this.chunkSize)
      })
      cur += this.chunkSize
    }
    console.log("🚀 ~ BigFileUploader ~ createChunks ~ chunks:", chunks)
    return chunks
  }

  // 计算文件哈希(Web Worker实现)
  calculateHash() {
    return new Promise(resolve => {
      const worker = new Worker(new URL('/src/views/learningRecord/bigFileUpload/hash-worker.js', import.meta.url), { type: 'module' })
      worker.postMessage({ file: this.file })
      worker.onmessage = e => {
        this.fileHash = e.data
        console.log("🚀 ~ BigFileUploader ~ calculateHash ~ this.fileHash:", this.fileHash)
        resolve()
      }
    })
  }

  // test

  // 开始上传
  async startUpload() {
    this.loaded = 0
    // 先检查哪些分片已上传
    const { uploaded } = await BigFileService.check({
      hash: this.fileHash,
      total: this.chunks.length
    })
    this.uploadedChunks = uploaded
    
    // 过滤出未上传的分片
    const toUpload = this.chunks.filter(
      chunk => !this.uploadedChunks.includes(chunk.index)
    )
    // 加入上传队列
    this.uploadingQueue = [...toUpload]

    // 控制并发
    const pool = []
    for (let i = 0; i < this.concurrent; i++) {
      pool.push(this.uploadNext())
    }

    await Promise.all(pool)
    
    // 所有分片上传完成后请求合并
    if (this.uploadedChunks.length === this.chunks.length) {
      await this.mergeChunks()
    }
  }

  // 控制并发上传
  async uploadNext() {
    while (this.uploadingQueue.length > 0) {
      const chunk = this.uploadingQueue.shift()
      await this.uploadChunk(chunk)
    }
  }

  // 上传单个分片
  async uploadChunk(chunk) {
    const formData = new FormData()
    formData.append('chunk', chunk.chunk)
    formData.append('hash', this.fileHash)
    formData.append('index', chunk.index)
    formData.append('total', this.chunks.length)
    try {
      await BigFileService.upload(formData)
      this.loaded++
      this.progressCallback({
        percent: (this.loaded / this.chunks.length * 100).toFixed(2)
      })
      this.uploadedChunks.push(chunk.index)
    } catch (err) {
      console.error(`分片${chunk.index}上传失败:`, err)
      // 可以加入重试机制
    }
  }

  

  // 请求合并分片
  async mergeChunks() {
    return BigFileService.merge({
      hash: this.fileHash,
      total: this.chunks.length,
      filename: this.file.name
    })
  }

  // 进度事件
  onProgress(callback) {
    // 可以在这里更新UI进度显示
    this.progressCallback = callback
  }
}

export default BigFileUploader;